package com.docker.sys.user.insideUserRole;

import com.docker.core.constant.MainConstant;
import com.docker.core.mvc.service.BaseService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.activerecord.tx.TxConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ldl
 * @Create 2020/09/23 023 10:01
 */
public class InsideUserRoleService extends BaseService {

    @Inject
    private InsideUserRoleDao insideUserRoleDao;

    public List<Record> tree(String userId) {
        List<Record> list = insideUserRoleDao.list(userId);
        List<Record> result = new ArrayList<>();
        for (Record deptRole : list) {
            if (StrKit.isBlank(deptRole.getStr("dept_code"))) {
                deptRole.set("dept_code", "-1");
            }
            if (StrKit.isBlank(deptRole.getStr("dept_name"))) {
                deptRole.set("dept_name", "未知部门");
            }
            List<Record> roles;
            Record role = contains(result, deptRole.getStr("dept_code"));
            if (role != null) {
                roles = role.get("roles", List.class);
                roles.add(deptRole);
            } else {
                role = new Record();
                role.set("dept_code", deptRole.getStr("dept_code"));
                role.set("dept_name", deptRole.getStr("dept_name"));
                roles = new ArrayList<>();
                roles.add(deptRole);
                role.set("roles", roles);
                result.add(role);
            }
        }

        return result;
    }

    private Record contains(List<Record> result, String deptCode) {
        for (Record deptRole : result) {
            if (StrKit.equals(deptCode, deptRole.getStr("dept_code"))) {
                return deptRole;
            }
        }
        return null;
    }

    public List<Record> now(String userId) {
        return insideUserRoleDao.now(userId);
    }

    @Before(Tx.class)
    @TxConfig(MainConstant.DB_DOCKER)
    public boolean update(String userId, String roleId) {
        insideUserRoleDao.deleteAll(userId);
        if (StrKit.notBlank(roleId)) {
            String[] ids = roleId.split(",", -1);
            for (String id : ids) {
                Record userRole = new Record();
                userRole.set("ur_id", getUUID32());
                userRole.set("user_id", userId);
                userRole.set("role_id", id);
                insideUserRoleDao.save(userRole);
            }
        }
        return true;
    }

    public boolean exist(String userId) {
        return insideUserRoleDao.exist(userId);
    }

}
